define([ 'angular'], function(angular) {
	'use strict';
	
	//var INTEGER_REGEXP = /^\-?1\d{2}$/;
	
	angular.module('baseinfo.fileFactorySingle', [])
	/*
	//自定义指令（提供数据唯一性验证）
	.directive('myInteger', function () {
                return {
                    require: 'ngModel',
                    link: function (scope, elm, attrs, ctrl) {
                        ctrl.$validators.myInteger = function (modelValue, viewValue) {
                            if (ctrl.$isEmpty(modelValue)) {
                                return true;
                            }

                            if (INTEGER_REGEXP.test(viewValue)) {
                                return true;
                            }

                            return false;
                        };
                    }
                };
            });
	*/
	.controller('fileFactorySingleCtrl'
			,[ '$rootScope', '$scope'
			   , '$uibModalInstance','params', 'title', 'BizData', f])//控制器结束
	
	function f($rootScope, $scope
			, $uibModalInstance, params, title, BizData
			) {

		var Model = this;
		
		//定义页面级别的变量
		var systemCode = $rootScope.winid; //系统代码
		var billType = 'GCDA';
		var billTypeName = "工厂";
		
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
			/*
			event.defaultValues.push({
				state:'active',
            	status:'open',
            	audit:'active',
            	autoOrder:'N'
            });
			*/
		}
		
		Model.dataMasterAfterRefresh = function(event) {
			//打开窗口之后，至于编辑状态
			Model.edit();
		}

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}



		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			console.log('column-->',event.column);
			console.log('value-->',event.value);
			if(event.column=='fProvince' || event.column=='fCity' || event.column=='fZone' || event.column=='fStreet' || event.column=='fStreetNumber'){
				var fProvince = event.source.getValue('fProvince',event.source.getID(event.rowIndex));
			    var tempProvince = fProvince;
			    //北京市 | 天津市 | 重庆市 | 上海市 | 香港特别行政区 | 澳门特别行政区
			    if (fProvince == '北京' || fProvince == '天津' || fProvince == '重庆' || fProvince == '上海'){
			      tempProvince = '';
			    } else if (fProvince == '香港' || fProvince == '澳门'){
			      tempProvince = fProvince + '特别行政区';
			    } else if (fProvince == '广西'){
			      tempProvince = fProvince + '壮族自治区';
			    } else if (fProvince == '宁夏') {
			      tempProvince = fProvince + '回族自治区';
			    } else if (fProvince == '新疆') {
			      tempProvince = fProvince + '维吾尔自治区';
			    } else if (fProvince == '西藏' || fProvince == '内蒙古') {
			      tempProvince = fProvince + '自治区';
			    } else {
			      tempProvince = fProvince + '省';
			    }
				
				var fCity = event.source.getValue('fCity',event.source.getID(event.rowIndex));
				var fZone = event.source.getValue('fZone',event.source.getID(event.rowIndex));
				var fStreet = event.source.getValue('fStreet',event.source.getID(event.rowIndex));
				if(!fStreet) fStreet = '';
				var fStreetNumber = event.source.getValue('fStreetNumber',event.source.getID(event.rowIndex));
				if(!fStreetNumber) fStreetNumber = '';
				//完整地址
				var fAddressDetail = tempProvince +fCity+fZone+fStreet+ fStreetNumber;
				console.log('fAddressDetail-->>',fAddressDetail);
				
				event.source.setValue('fAddressDetail', fAddressDetail , event.source.getID(event.rowIndex));
			}
		};
		


		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {
			console.log('dataMasterBeforeNew');
		};
		
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){
			console.log('dataMasterAfterNew-->>',event);

			event.source.setValue('iType', 0, event.id);//工厂
			event.source.setValue('taxType', 1, event.id);
			event.source.setValue('taxTypeLabel', '1.应税内含', event.id);
			event.source.setValue('taxRate', 0.17, event.id);

			//创建行后赋值
			event.source.setValue('systemCode',systemCode,event.id);
			event.source.setValue('billType',billType,event.id);
			event.source.setValue('billTypeName',billTypeName,event.id);
			
		}

		Model.dataMasterBeforeSave = function(event) {
			console.log('dataMasterBeforeSave-->>',event)
		};

		Model.dataMasterAfterSave = function(event) {
			//保存成功
			$uibModalInstance.close(0);
		};
		
		
		//地址解析
		Model.triggerGeocoderClick = function(){
     		var dataMaster = Model.dataMaster;
     		var rowID = dataMaster.getCurrentID();
     		var fAddress = dataMaster.getValue('fAddress', rowID);

			var options = {
				"address": fAddress
			};
			$.ajax({
				type : "GET",
				async : true,//异步加载
				dataType : "json",
				contentType: "application/json; charset=utf-8",
				url : $rootScope.getProjectName() + "/retail/lbs/geoencoder",  
				data: options,
				success : function(data, textStatus, jqXHR) {
					console.log('Model.triggerGeocoderClick.success.data-->',data);
					if(data.status==0){
//						Model.dataMaster = data.data;
						console.log('triggerGeocoderClick.result-->>',data.result);
						dataMaster.setValue('lng',data.result.location.lng,rowID);
						dataMaster.setValue('lat',data.result.location.lat,rowID);
						
						$scope.$apply();
					}else{
						alert("操作失败！"+data.message);
					}
				}
			 });
			
		};
		

		
		var options = {};
		options.container = Model;
		options.concept = 'FileFactory';
		options.name = 'dataMaster';
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/baseinfo/fileFactory/list/create';
		options.reader = '/baseinfo/fileFactory/list/query';
		options.writer = '/baseinfo/fileFactory/list/save';
		options.deleter = '/baseinfo/fileFactory/list/delete';
		options.valider = '/baseinfo/fileFactory/list/valid';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
//		options.defCols = {fID:{name:"fID",type:"String",label:""},systemCode:{name:"systemCode",type:"String",label:""},billType:{name:"billType",type:"String",label:""},billTypeName:{name:"billTypeName",type:"String",label:""},orderDate:{name:"orderDate",type:"Date",label:""},state:{name:"state",type:"String",label:""},status:{name:"status",type:"String",label:""},factoryNo:{name:"factoryNo",type:"String",label:""},factoryName:{name:"factoryName",type:"String",label:""},fAddressName:{name:"fAddressName",type:"String",label:""},fAddressDetail:{name:"fAddressDetail",type:"String",label:""},fAddress:{name:"fAddress",type:"String",label:""},fProvince:{name:"fProvince",type:"String",label:""},fCity:{name:"fCity",type:"String",label:""},fZone:{name:"fZone",type:"String",label:""},fStreet:{name:"fStreet",type:"String",label:""},fStreetNumber:{name:"fStreetNumber",type:"String",label:""},lat:{name:"lat",type:"Decimal",label:""},lng:{name:"lng",type:"Decimal",label:""},cityCode:{name:"cityCode",type:"String",label:""},contacts:{name:"contacts",type:"String",label:""},mobilePhone:{name:"mobilePhone",type:"String",label:""},fPhone:{name:"fPhone",type:"String",label:""},sMail:{name:"sMail",type:"String",label:""},faxPhone:{name:"faxPhone",type:"String",label:""},qqCode:{name:"qqCode",type:"String",label:""},postcode:{name:"postcode",type:"String",label:""},images:{name:"images",type:"String",label:""},summary:{name:"summary",type:"String",label:""},comments:{name:"comments",type:"String",label:""},cUsercode:{name:"cUsercode",type:"String",label:""},cUsername:{name:"cUsername",type:"String",label:""},cDatetime:{name:"cDatetime",type:"Datetime",label:""},tUsercode:{name:"tUsercode",type:"String",label:""},tUsername:{name:"tUsername",type:"String",label:""},tDatetime:{name:"tDatetime",type:"Datetime",label:""},eUsercode:{name:"eUsercode",type:"String",label:""},eUsername:{name:"eUsername",type:"String",label:""},eDatetime:{name:"eDatetime",type:"Datetime",label:""},sCreatorFID:{name:"sCreatorFID",type:"String",label:""},userId:{name:"userId",type:"String",label:""},enterpriseNo:{name:"enterpriseNo",type:"String",label:""},enterpriseName:{name:"enterpriseName",type:"String",label:""},iType:{name:"iType",type:"Integer",label:""},storeType:{name:"storeType",type:"String",label:""},storeTypeName:{name:"storeTypeName",type:"String",label:""},taxType:{name:"taxType",type:"Integer",label:""},taxTypeLabel:{name:"taxTypeLabel",type:"String",label:""},taxRate:{name:"taxRate",type:"Decimal",label:""},depositRate:{name:"depositRate",type:"Decimal",label:""},startTime:{name:"startTime",type:"Time",label:""},endTime:{name:"endTime",type:"Time",label:""},storageID:{name:"storageID",type:"String",label:""},storageNo:{name:"storageNo",type:"String",label:""},storageName:{name:"storageName",type:"String",label:""},floorNo:{name:"floorNo",type:"String",label:""},storageType:{name:"storageType",type:"String",label:""},storageTypeLabel:{name:"storageTypeLabel",type:"String",label:""},freeShipping:{name:"freeShipping",type:"Integer",label:""},startPrice:{name:"startPrice",type:"Decimal",label:""},renewPrice:{name:"renewPrice",type:"Decimal",label:""},startOrderAmount:{name:"startOrderAmount",type:"Decimal",label:""},freeOrderAmount:{name:"freeOrderAmount",type:"Decimal",label:""},weightsize:{name:"weightsize",type:"String",label:""},weightsizeLabel:{name:"weightsizeLabel",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
		options.defCols = '';
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fFID';
		options.directDeleteMode = true;
		options.limit = 15;
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onAfterRefresh = Model.dataMasterAfterRefresh;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);
		Model.dataMaster.init();

		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////
		//接收调用的参数
		Model.params = $rootScope.$stateParams;  
		
		////////////////////启动执行结束///////////////////////////////////////////////////
			

		
		
		//////////////////////对话框使用开始//////////////////////////////////////
        //模态窗口打开之后执行的事件
        $uibModalInstance.opened.then(function(){
    		//接收调用对话框的参数
    		Model.title = title;  
    		Model.params = params;  
//    	    Model.dataMaster.selected = {  
//    	        item: Model.dataMaster.items[0]  
//    	    };  
    		 
    		if(Model.params.recordState=='new'){
    			Model.dataMaster.loadData('');
	   		     var options = {
				         index : 0,
				         defaultValues : [
				             {
				            	 state:'active'
				            	 ,status:'open'
				            	 ,audit:'active'
				            	 ,lat: 0
				            	 ,lng: 0
				            	 ,depositRate: 0
				            	 ,freeShipping: 0
				            	 ,startPrice: 0
				            	 ,renewPrice: 0
				            	 ,startOrderAmount: 0
				            	 ,freeOrderAmount: 0
				            	 
				            	 ,orderDate: ':getCurrentDate()'
					             ,employeeNo: ':getCurrentPsmFID()'
						         ,employeeName: ':getCurrentPsmFName()'
					             ,cUsercode: ':getCurrentPersonCode()'
						         ,cUsername: ':getCurrentPersonName()'
							     ,cDatetime: ':getCurrentDateTime()'
								 ,userId: ':getCurrentPersonID()'
								 ,enterpriseNo: ':getCurrentOgnFID()'
								 ,enterpriseName: ':getCurrentOgnLongName()'
								 ,version: 0
				            }//,
	//			            {itemNo:'a2',itemDescribe:'b2'}
				         ]
				     };    
	
				Model.dataMaster.newData(options);
    		}
    		
    		if(Model.params.recordState=='edit'){
//    			Model.dataMaster.filter = "fID='"+params.id+"'";
    			Model.dataMaster.id = Model.params.id;
    		    Model.dataMaster.refreshData();
    		}
    		
        });  
		
		//修改
		Model.edit = function(){
			//Model.dataMaster.userdata.recordState = 'edit';
			Model.dataMaster.editData();
		};
		 
        Model.ok = function () {  
	    	Model.dataMaster.saveData();
	    };  
	    
	    Model.cancel = function () {  
	        $uibModalInstance.dismiss('cancel');  
	    };    
	    
		//////////////////////对话框使用结束//////////////////////////////////////

	    
	    
	}
	
	
});
